<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>glmatrix使用</title>
    <style>
      canvas {
        border: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script id="vertex-shader" type="x-shader/x-vertex">
      attribute vec4 aPosition; // 位置坐标
      uniform mat4 mScale; // 缩放矩阵
      void main() {
        gl_Position = mScale * aPosition; // 设置顶点位置
      }
    </script>

    <script id="fragment-shader" type="x-shader/x-fragment">
      void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // 设置颜色为红色
      }
    </script>
    <script type="module">
      import initShaders from "../utils/initShader.js";
      //   import { mat4 } from "gl-matrix"; // 导入gl-matrix库中的mat4模块
      import { mat4 } from "../libs/gl-matrix/esm/index.js"; // 使用ESM导入gl-matrix库中的mat4模块

      const canvas = document.getElementById("canvas");
      const gl = canvas.getContext("webgl");
      const program = initShaders(gl);

      // 等腰三角形
      const vertices = new Float32Array([-0.5, -0.5, 0.5, -0.5, 0, 0.5]);

      const buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

      const aPosition = gl.getAttribLocation(program, "aPosition");
      gl.vertexAttribPointer(
        aPosition,
        2,
        gl.FLOAT,
        false,
        2 * Float32Array.BYTES_PER_ELEMENT,
        0
      );
      gl.enableVertexAttribArray(aPosition);

      const mScale = gl.getUniformLocation(program, "mScale");
      const matrix = mat4.create(); // 创建一个单位矩阵，结果矩阵
      // 方法1：使用mat4.scale函数
      // mat4.scale(matrix, matrix, [0.2, 0.2, 1]); // 创建一个缩放矩阵，缩放因子为0.5
      // 方法2：手动创建缩放矩阵
      mat4.fromScaling(matrix, [0.5, 0.5, 1]); // 创建一个缩放矩阵，缩放因子为0.5
      gl.uniformMatrix4fv(mScale, false, matrix); // 将缩放矩阵传递给着色器

      gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2); // 绘制三角形
    </script>
  </body>
</html>
